package tt.dz.biz.service.cardno;

import org.apache.commons.lang3.math.NumberUtils;
import tt.dz.common.BusinessException;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.CardBIN;
import tt.dz.common.DzConstants.CardType;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CardErrorCode;
import tt.dz.vo.MerchantVO;

public class BuilderPatternNoCardSequeue
  implements CardNoCardConfigSequenceGenerator
{
  private String areaCode;
  private MerchantVO merchant;
  private DzConstants.CardBIN cardbin;
  private DzConstants.CardType cardType;
  private CardNoSeqHelpHandler handler = CardNoSeqHelpHandler.instance();
  
  public void setMerchant(MerchantVO merchant)
  {
    this.merchant = merchant;
  }
  
  public void setCardType(DzConstants.CardType cardType)
  {
    this.cardType = cardType;
  }
  
  public void setCardBin(DzConstants.CardBIN cardbin)
  {
    this.cardbin = cardbin;
  }
  
  public void setAreaCode(String areaCode)
  {
    this.areaCode = areaCode;
  }
  
  public String[] generator(int generatorCount)
    throws BusinessException
  {
    String currentMaxSeqNo = this.handler.getMaxSeqNoByBinTypeAreaSignalCodeLikeCardNo(this.cardType, this.cardbin, this.areaCode, this.merchant.getSignalCode());
    
    int currentSeqNo = NumberUtils.toInt(currentMaxSeqNo, 0);
    double retainCount = this.handler.retainCardSeqCount(currentMaxSeqNo);
    if (Double.compare(retainCount, generatorCount) < 0)
    {
      DzErrorCode.CardErrorCode cardErrorCode = DzErrorCode.CardErrorCode.RETAIN_SEQUEUE_INSUFFICIENT;
      throw new BusinessException(cardErrorCode.value(), cardErrorCode.getDesc(), "当前需求数量[" + retainCount + "]但可提供的数量[" + generatorCount + "]");
    }
    String seqNo = "";
    String[] seqNoes = new String[generatorCount];
    for (int i = 0; i < generatorCount; i++)
    {
      currentSeqNo++;
      seqNo = DZStringUtil.getFixedLengthString(this.handler.getSequenceLength(), String.valueOf(currentSeqNo));
      seqNoes[i] = seqNo;
    }
    return seqNoes;
  }
}
